//jquery cookie
jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '; path=/';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};


$(function(){
    
	if($(".playhistory").length) GetURecord();//观看记录
	if($(".myfavorite").length) GetUfav();//收藏列表
	if($("#fjinfo").length) { SetURecord(); }//播放页
	
	//回到顶部
	$("#back-top").click(function(){
        $("body,html").animate({scrollTop:0},500);
    });
	
	/**
	 * 返回顶部
	 */
	$(window).scroll(function(){
	    if ($(window).scrollTop()>100) {
	        $("#back-top").fadeIn(1500);
	    }else{
	        $("#back-top").fadeOut(1500);
	    }

	});
	
	//热门推荐ITEM移动效果
	$(".type-recommend-list .tab li").mouseover(function(){
		
		var $this = $(this);
		var index = $this.index();
		$(".type-recommend-list .tab li span").removeClass("current");
		$this.find('span').addClass("current");
		//$this.addClass("current").siblings("li").removeClass("current");
		$(".type-recommend-list .list").eq(index).show().siblings(".type-recommend-list .list").hide();
	});
	
	//动漫内页Nav浮动
	if($(".navitem").length >0) {
		var navTop = $(".navitem").offset().top;
    	navfix(navTop);
        $(window).scroll(function(){
        	navfix(navTop);
        });
    }
	
	//视频播放内页旁滚动条显示
	if($("#rank-wrap").length >0) {
		var bars = '.jspHorizontalBar, .jspVerticalBar';
		$('#rank-wrap').bind('jsp-initialised', function (event, isScrollable) {
			
			//hide the scroll bar on first load
			$(this).find(bars).hide();
		
		}).jScrollPane().hover(
		
			//hide show scrollbar
			function () {
				$(this).find(bars).stop().fadeTo('fast', 0.9);
			},
			function () {
				$(this).find(bars).stop().fadeTo('fast', 0);
			}

		);
	}
	
	//分享按钮移动上去效果
	var b = null;
    $("#shareBtn,#shareFloat").mouseenter(function() {
        clearTimeout(b);
        b = setTimeout(function() {
            $("#shareFloat").show()
        },
        200)
    }).mouseleave(function() {
        clearTimeout(b);
        b = setTimeout(function() {
            $("#shareFloat").hide()
        },
        200)
    });
	
	//观看记录移动事件
    var c = null;
    $("#history,.playhistory").mouseenter(function() {
        clearTimeout(c);
        c = setTimeout(function() {
        	$("#history-block").addClass("hover");
        },
        200)
    }).mouseleave(function() {
        clearTimeout(c);
        c = setTimeout(function() {
        	$("#history-block").removeClass("hover");
        },
        200)
    });
	
    //收藏记录移动事件
    var d = null;
    $("#collect,.myfavorite").mouseenter(function() {
        clearTimeout(d);
        d = setTimeout(function() {
        	$("#collect-block").addClass("hover");
        },
        200)
    }).mouseleave(function() {
        clearTimeout(d);
        d = setTimeout(function() {
        	$("#collect-block").removeClass("hover");
        },
        200)
    });
    
    //人物点赞移动事件
    var e = null;
    var mid = 0;
    $(".rank_people,.vote").mouseenter(function(event) {
    	mid = $(this).attr('data-id');
        clearTimeout(e);
        e = setTimeout(function() {
        	$('.vote').hide();
        	$('.vote-num').show;
        	var $rank = $("#rank"+mid);
        	$rank.find('.vote').css("display","block");
        	$rank.find('.vote-num').hide();
        },
        0)
    }).mouseleave(function(event) {
        clearTimeout(e);
        e = setTimeout(function() {
        	$('.vote').hide();
        	$('.vote-num').show();
        },
        0)
    });
    
});

//动漫内页Nav浮动
function navfix(navTop){
	if($(window).scrollTop()>navTop){
		$(".navitem").addClass("nav_fixed");
	}else{
		$(".navitem").removeClass("nav_fixed");	
	}

	var isMatch = false;
	var navSize = $(".f-click-jump").length;
	for(i=0;i<navSize;i++){
		var jumpTop = $(".f-click-jump").eq(i).offset().top;
		if($(window).scrollTop()>=jumpTop-40){
			if(isMatch == false){
				isMatch = true;
			}
			$(".navitem a").eq(i).addClass("current").siblings().removeClass("current");
		}
		if(isMatch == false){
			isMatch = $(".navitem a").eq(0).addClass("current").siblings().removeClass("current");
    	}
	}
}

//动漫内页nav item点击事件
function jumpto(id){
	$(window).scrollTop($(id).offset().top-40);
}

///<summary>
///	保存用户观看记录
///</summary>
function SetURecord() {
	// [动漫ID,动漫名称,分集ID,分集集数,观看时间]
	var dm = eval($("#fjinfo").text());
	thisdmid = dm[0];//必须定义为全局变量
	var str = "[['"+dm[0]+"','"+dm[1]+"','"+dm[2]+"','"+dm[3]+"','"+new Date().getTime()+"']";
	var temp = $.cookie("urecord");
	if (temp) {
		$.each(eval(temp),function(i,v) {
			if (i>=49) return false;// 总记录数不超过50条
			if (v[0]!=thisdmid) str += ",['" + v.join("','") + "']";
		});
	}
	str += "]";
	$.cookie("urecord",str,{ expires: 8760 });// 失效时间一年
}

///<summary>
///	读取用户观看记录
///</summary>
/// <param name="page">当前页码，默认为1</param>
function GetURecord(page) {
	if(!page) page = 1;
	var temp = $.cookie("urecord");
	if (!temp) {
		$(".playhistory").html("<span>您还没有任何观看记录！</span>");
		return;
	}
	
	var tmparr = eval(temp);
	var perpage = 10;//每页记录数
	var pagecount = Math.ceil(tmparr.length/perpage);//总页数
	var tmpstr = "<ul>";
	for(var i=(page-1)*perpage;i<page*perpage;i++) {
		if(i>=tmparr.length) break;
		tmpstr += '<li><a target="_self" href="javascript:" class="gray" onclick="return DelURecord('+tmparr[i][0]+')">[删]</a>'+date2str(tmparr[i][4],'MM.dd hh:mm')+' <a href="/html/movie/'+tmparr[i][0]+'/" class="title" title="'+tmparr[i][1]+'">'+tmparr[i][1]+'</a> 观看至 <a href="/html/movie/'+tmparr[i][0]+'/'+getfjurl(tmparr[i][2],tmparr[i][1],tmparr[i][3])+'" class="gray">'+tmparr[i][3]+'</a></li>';
	}
	if(tmpstr == "<ul>") { GetURecord(page-1);return false; }
	tmpstr += "</ul><div class=\"button\">";
	if(pagecount>1) {
		var tmpstr2 = "<div class=\"pages\">";
		if(page>1) tmpstr2 += "<a href=\"javascript:\" onclick=\"return GetURecord("+(page-1)+")\">上一页</a>";
		for(var i=1;i<=pagecount;i++) tmpstr2 += " <a href=\"javascript:\" onclick=\"return GetURecord("+i+")\""+(i==page?" class=\"thispage\"":"")+">"+i+"</a>";
		if(page<pagecount) tmpstr2 += " <a href=\"javascript:\" onclick=\"return GetURecord("+(page+1)+")\">下一页</a>";
		tmpstr2 += "</div>";
		tmpstr += tmpstr2;
	}
	tmpstr += "<a href=\"javascript:\" onclick=\"return DelURecord()\" class=\"clearall\">[清空记录]</a></div>"
	$(".playhistory").html(tmpstr);
	return false;
}

///<summary>
///	清除用户观看记录
///</summary>
function DelURecord(dmid) {
	if(dmid) {
		var str = "",deldmtitle;
		$.each(eval($.cookie("urecord")),function(i,v) {
			if (v[0]!=dmid) str += ",['" + v.join("','") + "']";
			else deldmtitle = v[1]+v[3];
		});
		str = "["+str.substr(1)+"]";
		if(str=="[]") str=null;
		$.cookie("urecord",str,{ expires: 8760 });// 失效时间一年
		if($(".playhistory .thispage").length) GetURecord($(".playhistory .thispage").text());
		else GetURecord();
		alert(deldmtitle+"的观看记录已被删除！");
	} else {
		$.cookie("urecord",null);
		$(".playhistory").html("<span>您没有任何观看记录！</span>");
		$(".toplink .hover").removeClass("hover");
		alert("您的观看记录已被清除");
	}
	return false;
}

/// <summary>
///	设置收藏动漫
/// </summary>
function SetUfav() {
	if(($.cookie("ufav")||",").indexOf("'"+$("#dmid").text()+"'")==-1) {
		var str = "[['"+$("#dmid").text()+"','"+$("#dmtitle").text().trim()+"']";
		//alert(str);
		var temp = $.cookie("ufav");
		if (temp) {
			$.each(eval(temp),function(i,v) {
				if (i>=49) return false;// 总记录数不超过50条
				if (v[0]!=$("#dmid").text()) str += ",['" + v.join("','") + "']";
			});
		}
		str += "]";
		$.cookie("ufav",str,{ expires: 8760 });// 失效时间一年
		alert($(".dmtitle").text().trim()+"已加入您在本站的收藏列表！（收藏列表在网站最顶部）");
		GetUfav();
	} else alert("您已收藏过该动漫，请勿重复操作！");
	return false;
}

/// <summary>
///	显示收藏动漫
/// </summary>
/// <param name="page">当前页码，默认为1</param>
function GetUfav(page) {
	
	if(!page) page = 1;
	var temp = $.cookie("ufav");
	if (!temp) {
		$(".myfavorite").html("<span>您还没有收藏任何动漫！</span>");
		return;
	}
	//alert(temp);
	var tmparr = eval(temp);
	
	var perpage = 10;//每页记录数
	var pagecount = Math.ceil(tmparr.length/perpage);//总页数
	var tmpstr = "<ul>";
	for(var i=(page-1)*perpage;i<page*perpage;i++) {
		if(i>=tmparr.length) break;
		tmpstr += '<li><a target="_self" href="javascript:" class="gray" onclick="return DelUfav('+tmparr[i][0]+')">[删]</a><a href="/html/movie/'+tmparr[i][0]+'/" target="_blank">'+tmparr[i][1]+'</a></li>';
	}
	tmpstr += "</ul><div class=\"button\">";
	if(pagecount>1) {
		var tmpstr2 = "<div class=\"pages\">";
		if(page>1) tmpstr2 += "<a href=\"javascript:\" onclick=\"return GetUfav("+(page-1)+")\">上一页</a>";
		for(var i=1;i<=pagecount;i++) tmpstr2 += " <a href=\"javascript:\" onclick=\"return GetUfav("+i+")\""+(i==page?" class=\"thispage\"":"")+">"+i+"</a>";
		if(page<pagecount) tmpstr2 += " <a href=\"javascript:\" onclick=\"return GetUfav("+(page+1)+")\">下一页</a>";
		tmpstr2 += "</div>";
		tmpstr += tmpstr2;
	}
	tmpstr += "<a href=\"javascript:\" onclick=\"return DelUfav()\" class=\"clearall\">[清空记录]</a></div>"
	$(".myfavorite").html(tmpstr);
	return false;
}

/// <summary>
///	删除收藏动漫
/// </summary>
function DelUfav(dmid) {
	if(dmid) {
		var str = "",deldmtitle;
		$.each(eval($.cookie("ufav")),function(i,v) {
			if (v[0]!=dmid) str += ",['" + v.join("','") + "']";
			else deldmtitle = v[1];
		});
		str = "["+str.substr(1)+"]";
		if(str=="[]") str=null;
		$.cookie("ufav",str,{ expires: 8760 });// 失效时间一年
		if($(".myfavorite .thispage").length) GetUfav($(".myfavorite .thispage").text());
		else GetUfav();
		alert(deldmtitle+"已从收藏列表中删除！");
	} else {
		$.cookie("ufav",null);
		$(".myfavorite").html("<span>您没有收藏任何动漫！</span>");
		$(".toplink .hover").removeClass("hover");
		alert("您的收藏列表已被清除");
	}
	return false;
}

/// <summary>
///	格式化显示日期时间
/// </summary>
/// <param name="x">待显示的日期时间，可以为数字形式</param>
/// <param name="y">需要显示的格式，例如yyyy-MM-dd hh:mm:ss</param>
function date2str(x,y) {
	if(!isNaN(x)) x = new Date(eval(x));
	if(!y) y = "yyyy-MM-dd hh:mm:ss";
	var z = {y:x.getFullYear(),M:x.getMonth()+1,d:x.getDate(),h:x.getHours(),m:x.getMinutes(),s:x.getSeconds()};
	return y.replace(/(y+|M+|d+|h+|m+|s+)/g,function(v) {return ((v.length>1?"0":"")+eval('z.'+v.slice(-1))).slice(-(v.length>2?v.length:2))});
}

/// <summary>
/// 得到分集url
/// <summary>
function getfjurl(n_fjid,s_dmtitle,s_fjtitle) {
	s_fjtitle = s_fjtitle.replace(/^第0*(\d+)集/,"$1");
	if(/^\d+$/.test(s_fjtitle) && s_fjtitle.length==1) s_fjtitle = "0" + s_fjtitle;//小于10补0
	if(/\d$/.test(s_dmtitle) && /^\d+/.test(s_fjtitle)) s_dmtitle = s_dmtitle + "_";//动漫名以数字结尾且分集名为数字的补一下划线
	return n_fjid+".htm";
}